package cn.main.core;

import cn.main.entity.sys.Role;
import cn.main.entity.sys.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.orm.hibernate4.HibernateTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Author: chengwei
 * Date:   2016/5/20
 * Time:   8:55
 */
public class SessionHelper {

    public static UserSession getUserSession(HttpServletRequest req) {
        
//        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
//        HibernateTemplate template = ac.getBean(HibernateTemplate.class);
        if (req == null) {
            throw new RuntimeException("session is not exist");
        }
        HttpSession session = req.getSession(true);
//        if (session.getAttribute(SessionKey.SESSION_KEY) == null) {
//            UserSession userSession = new UserSession();
//            User user = template.get(User.class,"aa4ac7c80cbf42d291d6cfdc24089626");
//            userSession.setUser(user);
//            List<?> a = template.getSessionFactory().openSession().createSQLQuery("SELECT r.* FROM sys_role r INNER JOIN sys_user_role ur ON r.role_id = ur.role_id WHERE ur.user_id = :user_id")
//                    .addEntity("r", Role.class)
//                    .setString("user_id",user.getUserId()).list();
//            
//            Set<Role> roleSet = new HashSet<>();
//            for (Object o : a) {
//                if (o instanceof Role) {
//                    roleSet.add((Role) o);
//                }
//            }
//            userSession.setRoles(roleSet);
//            session.setAttribute(SessionKey.SESSION_KEY,userSession);
//        }
        
        return (UserSession)session.getAttribute(SessionKey.SESSION_KEY);
    }
}
